package com.solace.thumbnailator.utils;


import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;

/**
 * 作者 CG
 * 时间 2021/1/9 17:59
 * 注释 线程池工具类
 */
@Slf4j
public class ThreadPoolUtil {
    //核心线程数量
    private static final int corePoolSize = 10;
    //最大线程数量
    private static final int maximumPoolSize = 20;
    private static final int keepAliveTime = 60;
    //队列初始化容量
    private static final int initQueueCapacity = 40;

    public static ThreadPoolExecutor threadPool;

    /**
     * 无返回值直接执行
     *
     * @param runnable
     */
    public static void execute(Runnable runnable) {
        getThreadPool().execute(runnable);
    }

    /**
     * 返回值直接执行,
     *
     * @param callable
     */
    public static <T> Future<T> submit(Callable<T> callable) {
        return getThreadPool().submit(callable);
    }

    /*
     * 判断是否是最后一个任务
     */
    protected static boolean isTaskEnd() {
        return threadPool.getActiveCount() == 0;
    }

    /*
     * 获取缓存大小
     */
    public static int getQueue() {
        return threadPool.getQueue().size();
    }

    /*
     * 获取线程池中的线程数目
     */
    public static int getPoolSize() {
        return threadPool.getPoolSize();
    }

    /*
     * 获取已完成的任务数
     */
    public static long getCompletedTaskCount() {
        return threadPool.getCompletedTaskCount();
    }


    /*
     * 关闭线程池
     */
    public static void shutdown() {
        threadPool.shutdown();
    }

    /**
     * dcs获取线程池
     *
     * @return 线程池对象
     */
    public static ThreadPoolExecutor getThreadPool() {
        if (threadPool != null) {
            return threadPool;
        } else {
            synchronized (ThreadPoolUtil.class) {
                if (threadPool == null) {
                    threadPool = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, TimeUnit.SECONDS,
                            new LinkedBlockingQueue<>(initQueueCapacity), new ThreadPoolExecutor.CallerRunsPolicy());
                }
                return threadPool;
            }
        }
    }

}
